﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls.Primitives;

namespace AttachedBehavior
{ 

   public class SelectionChangedBehavior
  {

    public static void SetSelectionChanged(DependencyObject target, ICommand value)
    {
      target.SetValue(SelectionChangedBehavior.SelectionChangedProperty, value);
    }


    public static DependencyProperty SelectionChangedProperty =
            DependencyProperty.RegisterAttached("SelectionChanged",
            typeof(ICommand),
            typeof(SelectionChangedBehavior),
            new UIPropertyMetadata(SelectionChangedBehavior.SelectedItemChanged));


    
    private static void SelectedItemChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
    {
      Selector element = target as Selector;
      if (element == null) throw new InvalidOperationException("target");
      if ((e.NewValue != null) && (e.OldValue == null))
      {
        element.SelectionChanged += SelectionChanged;
      }
      else if ((e.NewValue == null) && (e.OldValue != null))
      {
        element.SelectionChanged -= SelectionChanged;
      }
    }

    private static void SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
      Selector selector = sender as Selector;
      System.Diagnostics.Debug.Assert ( selector != null ) ;
      ICommand command = selector.GetValue(SelectionChangedBehavior.SelectionChangedProperty) as ICommand;
      if (command != null)
      {
          if ( command.CanExecute ( null )) 

          command.Execute(e);
      } 
    }
  }




}
